from rest_framework import serializers
from .models import Review, ReviewPhoto
from apps.accounts.serializers import UserSimpleSerializer
from apps.chefs.serializers import ChefBasicSerializer, ChefSerializer

class ReviewCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Review
        fields = [
            'order', 'food_quality', 'service', 'cleanliness',
            'comment', 'is_public'
        ]
        extra_kwargs = {
            'order': {'required': True},
            'food_quality': {'required': True},
            'service': {'required': True},
            'cleanliness': {'required': True}
        }

    def validate_order(self, value):
        if value.customer != self.context['request'].user:
            raise serializers.ValidationError("您只能评价自己的订单")
        if value.status != 'completed':
            raise serializers.ValidationError("只能评价已完成订单")
        if hasattr(value, 'review'):
            raise serializers.ValidationError("该订单已评价")
        return value

class ReviewSerializer(serializers.ModelSerializer):
    customer = UserSimpleSerializer(read_only=True)
    chef = ChefBasicSerializer(read_only=True)
    
    class Meta:
        model = Review
        fields = [
            'id', 'order', 'customer', 'chef',
            'food_quality', 'service', 'cleanliness',
            'overall_rating', 'comment', 'is_public',
            'created_at', 'updated_at'
        ]
        read_only_fields = [
            'overall_rating', 'created_at', 'updated_at'
        ]

    def get_customer(self, obj):
        if obj.is_anonymous:
            return {
                'name': '匿名用户',
                'avatar': None
            }
        return ChefSerializer(obj.customer).data
    
class ReviewPhotoSerializer(serializers.ModelSerializer):
    class Meta:
        model = ReviewPhoto
        fields = ['image', 'uploaded_at']
        read_only_fields = ['uploaded_at']

class ReviewImageUploadSerializer(serializers.Serializer):
    review_id = serializers.IntegerField(required=True)
    image = serializers.ImageField(required=True)

